package kr.co.exight.onApp;

import library.ActionClass;
import library.ExPreferenceManager;
import library.GCMHttpConnect;
import library.Library;
import library.Library.DialogChoiceYes;
import library.Variables;
import library.YonseiManager;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.google.android.gcm.GCMRegistrar;

public class ActivityCertificate extends Activity {
	/** Called when the activity is first created. */
	WebView wv;
	ExPreferenceManager preManager;

	private static final String TAG = "GCM";
	//자신의 Project ID 를 넣어주세요
	private static final String SENDER_ID = "242049221661";	
	
	int countFlag = 0;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_certificate);


		preManager = new ExPreferenceManager(this);
		Variables.myNewFace = Typeface.createFromAsset(this.getAssets(), "fonts/Applemint.ttf");


		if(preManager.getItem(ExPreferenceManager.TAG_AUTOLOGIN) != ""){ // 처음 접속이 아닐시에
			Library.startActivity(this, ActivityMain.class);

			Variables.IS_CERTIFICATED = true;
			Variables.LOGIN_ID = preManager.getItem(ExPreferenceManager.TAG_ID);
			Variables.PASSWORD = preManager.getItem(ExPreferenceManager.TAG_PW);
			
		}else { // 처음 접속시에
			wv = (WebView)findViewById(R.id.login_inviWebView);
			RelativeLayout rl = (RelativeLayout)findViewById(R.id.login_rl);


			final EditText ed = (EditText)findViewById(R.id.login_etNumber);
			final EditText edPw = (EditText)findViewById(R.id.login_etPass);
			final ToggleButton tbLogin = (ToggleButton)findViewById(R.id.login_tbAutoLogin);
			final TextView tvAutoLogin = (TextView)findViewById(R.id.login_tvAutoLogin);

			rl.setOnTouchListener(new OnTouchListener() {

				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					mgr.hideSoftInputFromWindow(ed.getWindowToken(), 0);
					if(ed.hasFocus() && ed.getText().toString().length() > 5){
						edPw.requestFocus();
					}
					return false;
				}
			});
			Library.setFontNanumGothic(ed);
			Library.setFontNanumGothic(edPw);
			Library.setFontNanumGothic(tvAutoLogin);

			InputMethodManager im = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
			im.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);


			GCMRegistrar.checkDevice(this);
	        // 매니페스트 설정이 올바른지 확인
	        GCMRegistrar.checkManifest(this);
	        
			final String regId = GCMRegistrar.getRegistrationId(ActivityCertificate.this);
	      	//등록된 ID가 없으면 ID값을 얻어옵니다
	      	
			Button btnEnter = (Button)findViewById(R.id.login_btnLogin);


			btnEnter.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {					
					
//					if(preManager.getItem("KeyRegister").equals("")){
//						Toast.makeText(ActivityCertificate.this, "Key를 등록중입니다. 잠시 후에 다시 인증해주세요.", Toast.LENGTH_LONG).show();
//						return;
//					}

					// TODO Auto-generated method stub
					final String id = ed.getText().toString();
					final String pw = edPw.getText().toString();
					showDialog(0); // 로딩바 키기
					YonseiManager.getCertificate(wv, new ActionClass(ActivityCertificate.this) {	
						@Override
						public void actionFailed(int errCode) {
							// TODO Auto-generated method stub
							dismissDialog(0);
							if(errCode == YonseiManager.INPUT_ERROR){
								Library.makeYesDialog(ActivityCertificate.this, "학번과 패스워드가 맞지 않습니다.", "확인", new DialogChoiceYes() {

									public boolean choiceYes() {
										// TODO Auto-generated method stub
										ed.setText("");
										edPw.setText("");
										ed.requestFocus();
										return false;
									}
								});
							}else if (errCode == YonseiManager.CONNECTION_ERROR){
								Library.makeYesDialog(ActivityCertificate.this, "인터넷 연결이 좋지 않습니다.\n연결을 확인해주세요", "확인", new DialogChoiceYes() {

									public boolean choiceYes() {
										// TODO Auto-generated method stub
										ed.requestFocus();
										return false;
									}
								});
							}
						}

						@Override
						public void actionSuccess() {
							// TODO Auto-generated method stub
			
							if(GCMRegistrar.isRegistered(ActivityCertificate.this)){
								String regId = GCMRegistrar.getRegistrationId(ActivityCertificate.this);
						      		if(preManager.getItem("KeyRegister").equals("")){
						      			GCMHttpConnect httpConnect = new GCMHttpConnect(ActivityCertificate.this, Variables.NOTIFICATION_ADD_URL +  regId +
						      			"/add", 0);
						      			httpConnect.start();
						      		}
							}
					      	
							try{
								dismissDialog(0);
							}catch(IllegalArgumentException e){
								e.printStackTrace();
							}
							wv = null;

							if(tbLogin.isChecked()){
								preManager.putItem(ExPreferenceManager.TAG_AUTOLOGIN, "TRUE");
								preManager.putItem(ExPreferenceManager.TAG_ID, id);
								preManager.putItem(ExPreferenceManager.TAG_PW, pw);
							}

							Variables.IS_CERTIFICATED = true;

							Variables.LOGIN_ID = id;
							Variables.PASSWORD = pw;
							Library.startActivity(ActivityCertificate.this, ActivityMain.class);
						}

					},id, pw);				
				}
			});
		}

	}



	public void onBackPressed() {
		// TODO Auto-generated method stub
		countFlag++;
		if(countFlag == 2){
			Library.makeYesNoDialog(this, "ONApp을 종료하시겠습니까?", "확인", "취소", new Library.DialogChoiceYesNo() {

				public boolean choiceYes() {

					// TODO Auto-generated method stub
					finish();
					return false;
				}

				public boolean choiceNo() {
					// TODO Auto-generated method stub
					countFlag = 0;
					return false;
				}
			});
		}

	}
	@Override // 로딩바 안보이게 하기
	protected Dialog onCreateDialog(int id) {
		final Dialog dialog = new Dialog(this, R.style.Theme_Dialog);
		View view = getLayoutInflater().inflate(R.layout.dialog_progress, null);
		dialog.setContentView(view);
		dialog.setCancelable(false);
		return dialog;

	}


}

